using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Browser;
using System.Xml;
using System.Xml.Linq;

namespace Silverlight.Weblog.Client.Default.Widgets.TwitterSiderbar
{
    // Based on Guy Burstein's blog post @ 
    // http://blogs.msdn.com/bursteg/archive/2009/05/29/twitter-api-from-c-getting-a-user-s-time-line.aspx
    public class TwitterTimelineParser : ITwitterTimelineParser
    {
        #region Implementation of ITwitterTimelineParser

        public List<TwitterStatus> Parse(string UserTimelineUnparsed)
        {
            XDocument document = XDocument.Parse(UserTimelineUnparsed, LoadOptions.None);

            var query = from e in document.Root.Descendants("status")
                        select new TwitterStatus()
                        {
                            UserName = e.Element("user").Element("name").Value,
                            ProfileImage = e.Element("user").Element("profile_image_url").Value,
                            Status = HttpUtility.HtmlDecode(e.Element("text").Value),
                            StatusDate = ParseDateTime(e.Element("created_at").Value)
                        };

            List<TwitterStatus> users = (from u in query
                          where u.Status != ""
                             && !u.Status.StartsWith(@"@")
                          orderby u.StatusDate descending
                          select u).ToList();

            return users;
        }

        private static DateTime ParseDateTime(string date)
        {
            string dayOfWeek = date.Substring(0, 3).Trim();
            string month = date.Substring(4, 3).Trim();
            string dayInMonth = date.Substring(8, 2).Trim();
            string time = date.Substring(11, 9).Trim();
            string offset = date.Substring(20, 5).Trim();
            string year = date.Substring(25, 5).Trim();
            string dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time);
            DateTime ret = DateTime.Parse(dateTime);
            return ret;
        }

        #endregion
    }
}